<template>
  <el-form
    class="vae-form"
    :model="value"
    ref="form"
    label-position="left"
    :label-width="formConfig.labelWidth"
  >
    <div v-if="type == 'info'">
      <vaeFormInfo
        v-for="(item, index) in formConfig.column"
        :key="index"
        :item="item"
        :value="value[item.prop]"
        class="info-item flex align-center"
      >
      </vaeFormInfo>
    </div>
    <div v-else>
      <vaeFormItem
        v-for="(item, index) in formConfig.column"
        :key="index"
        :item="item"
        :value="value[item.prop]"
        :otherValue="value[item.prop]"
        @input="handleInput($event, item.prop)"
        class="info-item flex align-center"
      >
      </vaeFormItem>
    </div>
    <div class="menu">
      <el-button type="primary" @click="handleClose">取消</el-button>
      <el-button v-if="type == 'add'" type="primary" @click="handleAdd"
        >确定</el-button
      >
      <el-button v-if="type == 'edit'" type="primary" @click="handleEdit"
        >修改</el-button
      >
      <el-button
        v-if="type == '' || type == 'info'"
        type="primary"
        @click="handleClose"
        >确定</el-button
      >
    </div>
  </el-form>
</template>

<script>
import vaeFormItem from "@/components/vae-form-item";
import vaeFormInfo from "@/components/vae-form-info";
export default {
  name: "vae-form",
  components: { vaeFormItem, vaeFormInfo },
  props: {
    formConfig: {
      type: Object,
      required: true,
    },
    value: {
      type: Object,
      required: true,
    },
    type: {
      type: String,
      default: "",
    },
  },
  data() {
    return {};
  },
  mounted() {
    this.setDefaultValue();
  },
  methods: {
    setDefaultValue() {
      const formData = { ...this.value };
      // 设置默认值
      this.formConfig.column.forEach(({ prop, value }) => {
        if (formData[prop] === undefined || formData[prop] === null) {
          formData[prop] = value ||'';
        }
      });
      this.$emit("input", formData);
    },
    handleInput(val, key) {
      this.$emit("input", { ...this.value, [key]: val });
    },
    handleClose() {
      this.$emit("close");
    },
    // 添加
    handleAdd() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$emit("row-save");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleEdit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$emit("row-edit");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.menu {
  padding-left: 35px;
}
.vae-form {
  /deep/ .el-form-item__content {
    width: 100%;
  }
}
</style>